import java.util.LinkedList;

public class Semaphore{
	private int count;
	private LinkedList<Integer> philosophersEating;
	private int diners;
	
	public Semaphore(int newCount, int newDiners){
		count= newCount;
		diners = newDiners;
		philosophersEating = new LinkedList<Integer>();
	}

	public Semaphore(){
		count= 0;
	}

	public synchronized void V(int id){
		philosopher_finish(id);
		count++;
		notifyAll();
	}

	public synchronized void P(int id){
		try{
			System.out.println("Can enter philosopher "+id+ " = "+ canEat(id));
			while(count == 0 || !canEat(id))
				wait();
			philosopher_eating(id);
		}catch(InterruptedException e){};
		count--;
	}
	
	private boolean canEat(int id){
		boolean philosopher_can_eat = true;
		for(int i=0; i<philosophersEating.size();i++){
			if(philosophersEating.get(i) == 0 && id == diners-1)
				return false;
			if(philosophersEating.get(i) == diners-1 && id == 0)
				return false;
			if(philosophersEating.get(i) == id+1 || philosophersEating.get(i) == id-1)
				return false;
		}
		return philosopher_can_eat;
	}
	
	private void philosopher_eating(int id){
		philosophersEating.add(id);
	}
	
	private void philosopher_finish(int id){
		for(int i=0; i<philosophersEating.size();i++){
			if(philosophersEating.get(i) == id){
				philosophersEating.remove(i);
				System.out.println("Philosopher: "+id+" Finish");
			}
		}
	}
}
